package com.spark.core;
//package com.spark.core;
//
//import java.io.IOException;
//import java.io.PrintWriter;
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.Iterator;
//import java.util.List;
//import java.util.Map;
//import java.util.Set;
//
//import javax.servlet.ServletException;
//import javax.servlet.http.HttpServlet;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//
//import org.apache.catalina.CometEvent;
//import org.apache.catalina.CometProcessor;
//
//import com.spark.util.MemcachedHelper;
//
///**
// * Comet Facade.
// * 
// * @version $Id: SparkCometFacade.java v 1.0 2011-12-22 下午06:40:50 IBM Exp $
// * @author <a href="mailto:njq.niu@hand-china.com">vincent</a>
// * 
// * CODE: 1: no suk 2: no session 3: timeout 4: login conflict 5: other error
// * 
// * TODO: 改造成单独的SessionServer,不用memcache来处理list,而是SessionServer来自己处理自己的列表
// * 
// */
//public class SparkCometFacade extends HttpServlet implements CometProcessor {
//
//	private static final long serialVersionUID = -1303619831084860739L;
//
//	public static List<String> disconnect_list = new ArrayList<String>();
//
//	private MessageReceiver messageReceiver = null;
//	private Thread messageSenderThread = null;
//	private Map<String, HttpServletResponse> connections = new HashMap<String, HttpServletResponse>();
//
//	public void init() throws ServletException {
//		messageReceiver = new MessageReceiver();
//		messageSenderThread = new Thread(messageReceiver, "MessageReceiver["+ getServletContext().getContextPath() + "]");
//		messageSenderThread.setDaemon(true);
//		messageSenderThread.start();
//		System.out.println("SparkCometFacade Start");
//	}
//
//	public static void addDisconnectItem(String key) {
//		synchronized (disconnect_list) {
//			disconnect_list.add(key);
//			disconnect_list.notify();
//		}
//	}
//
//	public void destroy() {
//		messageReceiver.stop();
//		messageReceiver = null;
//		messageSenderThread.interrupt();
//	}
//
//	@SuppressWarnings("unchecked")
//	public void event(CometEvent event) throws IOException, ServletException {
//		HttpServletRequest request = event.getHttpServletRequest();
//		HttpServletResponse response = event.getHttpServletResponse();
//		String suk = (String) event.getHttpServletRequest().getParameter(SparkContext.SPARK_USER_KEY);
//
//		if (event.getEventType() == CometEvent.EventType.BEGIN) {
//			request.setCharacterEncoding(SparkConfiguration.DEFAULT_ENCODING);
//			response.setCharacterEncoding(SparkConfiguration.DEFAULT_ENCODING);
//			response.setContentType(SparkConfiguration.CONTENT_TYPE_JSON);
//			event.setTimeout(60000);
//			if (suk != null && !"".equals(suk)) {
//				String value = (String) MemcachedHelper.get(suk);
//				System.out.println(value + "   " + suk);
//				if (value == null) {
//					PrintWriter writer = response.getWriter();
//					writer.println("{success:false,code:2}");
//					writer.flush();
//					event.close();
//				} else {
//					MemcachedHelper.set(suk, 90, value);
//					synchronized (connections) {
////						System.out.println("put response " + suk + "   " + response);
//						connections.put(suk, response);
//					}
//				}
//
//			} else {
//				PrintWriter writer = response.getWriter();
//				writer.println("{success:false,code:1}");
//				writer.flush();
//				event.close();
//			}
//		} else if (event.getEventType() == CometEvent.EventType.ERROR) {
//			if (CometEvent.EventSubType.TIMEOUT == event.getEventSubType()) {
//				System.out.println("Timeout for session: " + suk);
//				PrintWriter writer = response.getWriter();
//				writer.println("{success:true,code:3}");
//				writer.flush();
//			} else if (CometEvent.EventSubType.CLIENT_DISCONNECT == event.getEventSubType()) {
//				System.out.println("CLIENT_DISCONNECT for session: " + suk);
//			} else {
//				PrintWriter writer = response.getWriter();
//				writer.println("{success:false,code:5}");
//				writer.flush();
//				System.out.println("Error for session: " + suk + "  "+ event.getEventSubType());
//			}
//			synchronized (connections) {
//				connections.remove(suk);
//			}
//			event.close();
//		} else if (event.getEventType() == CometEvent.EventType.END) {
//			System.out.println("End for session: " + suk);
//			if (suk != null && !"".equals(suk)) {
//				String sukey = (String) MemcachedHelper.get(suk);
//				if (sukey != null) {
//					String[] arr = sukey.split("#");
//					if (arr.length == 4) {
//						Integer userId = Integer.valueOf(arr[0]);
//						Integer companyId = Integer.valueOf(arr[1]);
//						String companyKey = "C" + companyId;
//						String userKey = userId + "_" + suk;
//						List userList = (List) MemcachedHelper.get(companyKey);
//						if (userList != null && userList.indexOf(userKey)!=-1) {
//							userList.remove(userKey);
//							MemcachedHelper.set(companyKey, 0, userList);
//						}
//					}
//				}
//				MemcachedHelper.delete(suk);
//			}
//			synchronized (connections) {
//				connections.remove(suk);
//			}
//			event.close();
//		}
//
//	}
//
//	public class MessageReceiver implements Runnable {
//
//		protected boolean running = true;
//
//		public void stop() {
//			running = false;
//		}
//
//		/**
//		 * TODO:需要考虑线程安全问题...
//		 */
//		@SuppressWarnings("unchecked")
//		public void run() {
//			while (running) {
//				if (disconnect_list.size() == 0) {
//					try {
//						synchronized (disconnect_list) {
//							disconnect_list.wait();
//						}
//					} catch (InterruptedException e) {
//						// Ignore
//					}
//				}
//				synchronized (connections) {
//					String[] pendingMessages = null;
//					synchronized (disconnect_list) {
//						pendingMessages = disconnect_list.toArray(new String[0]);
//						disconnect_list.clear();
//					}
//					
//					Set set = connections.keySet();
//					Iterator it = set.iterator();
//					while (it.hasNext()) {
//						String suk = (String) it.next();
//						String sukey = (String) MemcachedHelper.get(suk);
//						if (sukey != null) {
//							String[] arr = sukey.split("#");
//							if (arr.length == 4) {
//								String userId = arr[0];
//								String companyId = arr[1];
//								for (int j = 0, len = pendingMessages.length; j < len; j++) {
//									String mkey = pendingMessages[j];
//									String[] ps = mkey.split("_");
//									String pcompanyId = ps[0];
//									String puserId = ps[1];
//									String psuk = ps[2];
//									if (puserId.equals(userId) && pcompanyId.equals(companyId) && !psuk.equals(suk)) {
//										HttpServletResponse response = connections.get(suk);
//										System.out.println("kick session:" + suk);
//										if (response != null) {
//											PrintWriter writer;
//											try {
////												System.out.println("KICK RESPONSE " + response);
//												writer = response.getWriter();
//												writer.println("{success:true,code:4}");
//												writer.flush();
//												writer.close();
//											} catch (IOException e) {
//												e.printStackTrace();
//											}
//										}
//									}else{
//										System.out.println("skip session:" + suk);
//									}
//								}
//							}
//						}
//					}
//				}
//			}
//		}
//	}
//}
